package com.seoultour.joel;

import com.seoultour.joel.dao.LocationDao;
import com.seoultour.joel.entity.Location;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import twitter4j.*;

import java.util.List;

@Service
public class JoelStatusListener implements StatusListener {

	private long lastUpdateTime = 0L;
	private List<Location> locations;

	@Autowired
	private LocationDao locationDao;

	@Autowired
	private Registry registry;

	@Override
	public void onStatus(Status status) {
		update();
		String text = status.getText();
		if (status.getIsoLanguageCode().contains("ko")) {
			for (Location loc : locations) {
				if (text.contains(loc.getTitle())) {
					registry.save(text);
				}
			}
		}
	}

	private void update() {
		long time = System.currentTimeMillis();
		if (time - lastUpdateTime > 5.0*1000*1000) {
			locations = locationDao.getLocations();
			lastUpdateTime = time;
		}
	}

	@Override
	public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
	}

	@Override
	public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
	}

	@Override
	public void onScrubGeo(long userId, long upToStatusId) {
	}

	@Override
	public void onStallWarning(StallWarning warning) {
	}

	@Override
	public void onException(Exception ex) {
		ex.printStackTrace();
	}

	public void run() {
		TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
		twitterStream.addListener(this);

		twitterStream.sample();
	}
}
